﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace GmSm.common
{
    public static class LogHelper
    {
        private static string LogPath
        {
            get
            {
                return AppDomain.CurrentDomain.BaseDirectory + @"\log";
            }
        }

        /// <summary>
        /// 保存日志
        /// </summary>
        /// <param name="message">消息</param>
        /// <param name="methodName">方法名</param>
        public static void Message(string message, string methodName = "")
        {
            StringBuilder integrate = new StringBuilder();

            if (string.IsNullOrWhiteSpace(methodName))
                methodName = (new StackTrace()).GetFrame(1).GetMethod().Name; // 获取调用日志的方法名

            if (string.IsNullOrEmpty(message))
                return;

            var path = string.Format(@"\{0}\", DateTime.Now.ToString("yyyy-MM-dd"));
            integrate.AppendFormat($"{Environment.NewLine}=========={methodName}=========={DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
            integrate.AppendFormat("{1}     Message:{0}{1}", message, Environment.NewLine);
            WriteLog(path, "", integrate.ToString());
        }

        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="path"></param>
        /// <param name="prefix"></param>
        /// <param name="message"></param>
        private static void WriteLog(string path, string prefix, string message)
        {
            try
            {
                path = $"{LogPath}{path}";
                var fileName = $"{prefix}{DateTime.Now.ToString("yyyy-MM-dd")}";

                FileInfo fi = new FileInfo($"{path}{fileName}.log");
                if (fi.Exists)
                {
                    if (fi.Length / 1024 > 2000)
                    {
                        string newfilename = string.Empty;
                        int index = 1;
                        while (true)
                        {
                            newfilename = $"{path}{fileName}_{index}.log";
                            if (File.Exists(newfilename))
                            {
                                index += 1;
                            }
                            else
                            {
                                fi.MoveTo(newfilename);
                                break;
                            }
                        }
                    }
                }

                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);

                using (FileStream fs = new FileStream($"{path}{fileName}.log", FileMode.Append, FileAccess.Write, FileShare.Write, 1024, FileOptions.Asynchronous))
                {
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(message + Environment.NewLine);
                    IAsyncResult writeResult = fs.BeginWrite(buffer, 0, buffer.Length,
                        (asyncResult) =>
                        {
                            var fStream = (FileStream)asyncResult.AsyncState;
                            fStream.EndWrite(asyncResult);
                        }, fs);
                    fs.Close();
                }
            }
            finally { }
        }
    }
}
